<template>
	<view class="content b-t">
		<empty v-if="merchantList.length === 0"></empty>
		<u-cell-group title="选择门店">
			<u-cell-item :index="index" @click="selectMerchant" :arrow="true" :use-label-slot="true" :value="item.distance?('距您'+item.distance+'公里'):'未获取到当前位置'" :label="item.merchantAddress" :title="item.merchantName"  v-if="!item.closed" v-for="(item,index) in merchantList">
				<u-image width="100rpx" height="100rpx" :fade="true" :lazy-load="true" shape="circle" slot="icon" :src="applicationConfig.applicationLogo">
					<u-loading slot="loading"></u-loading>
				</u-image>
			</u-cell-item>
		</u-cell-group>
	</view>
</template>

<script>
	import empty from "@/components/empty";
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		components: {
			empty
		},
		data() {
			return {
				title: 'map',
				latitude: null,	
				longitude: null,
				scale: 10,
				showLocation: true,
				covers: [],
				merchantList: []
			}
		},
		onLoad(option) {
			let that = this;
			uni.getLocation({
				type: 'gcj02',
				success: function(res) {
					console.log('当前位置的经度：' + res.longitude);
					console.log('当前位置的纬度：' + res.latitude);
					that.latitude = res.latitude;
					that.longitude = res.longitude;
				},
				fail: function(res) {
					console.log('获取当前位置失败');
				},
				complete: function(res) {
					that.inquiryMerchant();
				}
			});
		},
		computed: {
			...mapState(['hasLogin', 'userInfo','merchant','applicationConfig'])
		},
		methods: {
			...mapMutations(['changeMerchant']),
			selectMerchant(index){
				this.changeMerchant(this.merchantList[index]);
				uni.navigateBack()
			},
			openLocation(item){
				uni.openLocation({
					latitude: item.latitude,
					longitude: item.longitude,
					success: function () {
						console.log('打开地图成功');
					}
				});
			},
			//查询门店列表
			inquiryMerchant() {
				let that = this;
				this.$api.request.merchantList({
					
				}, res => {
					if (res.body.status.statusCode === '0') {
						var merchantList = res.body.data.merchants;
						if(this.latitude && this.longitude){
							this.merchantList = this.sortMerchant(merchantList);
						}else{
							this.merchantList = merchantList;
						}
					} else {
						this.$api.msg(res.body.status.errorDesc);
					}
				});
			},
			sortMerchant(merchantList){
				let that = this;
				let distanceMerchantList = [];
				merchantList.forEach(function(val,index){
					let distance = that.$api.util.getDistance(that.latitude, that.longitude,val.latitude,val.longitude);
					val.distance = distance.toFixed(3);
					distanceMerchantList.push(val);
				})
				distanceMerchantList.sort(function(a,b){
					return a.distance-b.distance;
				})
				return distanceMerchantList;
			}
		}
	}
</script>

<style lang='scss'>
	page {
		padding-bottom: 120upx;
	}

	.content {
		position: relative;
	}
</style>
